using Microsoft.SharePoint;

namespace RealDolmen.SharePoint.Helpers
{
    public class TokenFixer
    {
        #region Fields
        private string webUrl;
        private string siteUrl; 
        #endregion // Fields

        #region Constructor
        public TokenFixer(SPWeb web)
        {
            // web.Site should not be disposed
            siteUrl = web.Site.ServerRelativeUrl;
            webUrl = web.ServerRelativeUrl;
        } 
        #endregion // Constructor

        #region Business Methods
        public string FixUrl(string url)
        {
            if (Process(ref url, "~sitecollection", siteUrl))
                return url;

            if (Process(ref url, "~site", webUrl))
                return url;

            return url;
        }

        private bool Process(ref string url, string prefix, string baseUrl)
        {
            int idx = url.ToLower().IndexOf(prefix.ToLower());
            if (idx > -1)
            {
                url = baseUrl + url.Substring(idx + prefix.Length);
                return true;
            }
            return false;
        } 
        #endregion // Business Methods
    }
}
